package com.yz.system.UI;

import java.io.DataInputStream;
import java.net.Socket;

public class ClientReaderThread extends Thread{
    private Socket socket;
    private DataInputStream dis;
    private ClientChatFrame win;
    public ClientReaderThread(Socket socket,ClientChatFrame win){
        this.socket = socket;
        this.win = win;
    }

    @Override
    public void run() {
        try {
            //规定一个消息类型1代表更新在线人数2代表群聊消息3代表私聊
            //先从socket管道中读取消息类型编号
            dis = new DataInputStream(socket.getInputStream());//获取输入流
            while (true) {
                int msgType = dis.readInt();//读取消息类型编号
                switch (msgType){
                    case 1:
                        updateClientOnLineUserList();
                        break;
                    case 2:
                        sendMsg();
                        break;
                    case 3:
                        sendMsg3();
                        //将标题设置为对某个用户的私聊
                        break;
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendMsg3() throws Exception {
        String sender = dis.readUTF(); // 获取发送方用户名
        String msg = dis.readUTF(); // 获取消息内容

        // 显示私聊消息
        win.sendMsg(sender + ": " + msg);
    }


    private void sendMsg() throws Exception {
            String msg = dis.readUTF();
            win.sendMsg(msg);
    }

    private void updateClientOnLineUserList() throws Exception {
        int count = dis.readInt();
        String[] onLineNames = new String[count];
        for(int i = 0; i < count; i++){
            String nickname = dis.readUTF();
            onLineNames[i] = nickname;
        }
        win.updateOnlineUsers(onLineNames);
    }


}
